package com.csw.android.localplayer.ui.local

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.csw.android.dev_utils.ex.FragmentEx.bindVM
import com.csw.android.dev_utils.ex.ViewEx.pxInt
import com.csw.android.dev_utils.ui.databinding.DataBindingFragment
import com.csw.android.dev_utils.utils.TableMarginDecoration
import com.csw.android.localplayer.R
import com.csw.android.localplayer.databinding.UiLocalListBinding
import com.csw.android.player.PlayerManager
import com.csw.android.player.base.MediaInfo
import com.csw.android.player.view.video.VideoView
import com.csw.android.player.view.window.VideoFloatWindow
import com.scwang.smart.refresh.layout.constant.RefreshState

class LocalListFragment : DataBindingFragment<UiLocalListBinding>() {
    private val localViewModel by lazy { bindVM<LocalViewModel>() }
    private var mediaLayoutManager: LinearLayoutManager? = null
    private var mediaAdapter: MediaAdapter? = null
    private var userInDragging = false
    private val playingMediaListener = Observer<MediaInfo?> {
        it ?: return@Observer
        if (userInDragging) {
            return@Observer
        }
        mediaAdapter?.run {
            data.indexOf(it).run {
                if (this >= 0) {
                    val c = dataBinding?.recyclerView?.context ?: return@Observer
                    val linearSmoothScroller = object : LinearSmoothScroller(c) {
                        override fun getVerticalSnapPreference(): Int {
                            return SNAP_TO_START
                        }
                    }
                    linearSmoothScroller.targetPosition = this
                    mediaLayoutManager?.startSmoothScroll(linearSmoothScroller)
                }
            }
        }
    }

    override fun getContentViewID() = R.layout.ui_local_list

    override fun initView(rootView: View, savedInstanceState: Bundle?) {
        super.initView(rootView, savedInstanceState)
        activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        dataBinding?.run {
            smartRefreshLayout.run {
                setEnableLoadMore(false)
                setOnRefreshListener {
                    localViewModel.getLocalMedia()
                }
            }
            recyclerView.run {
//                LinearSnapHelper().attachToRecyclerView(this)
                mediaLayoutManager = LinearLayoutManager(context)
                layoutManager = mediaLayoutManager
                addItemDecoration(object : TableMarginDecoration() {
                    private val dp16 = pxInt(16f)
                    private val dp10 = pxInt(10f)
                    private val dp5 = pxInt(5f)
                    override fun getItemOffset(
                        view: View,
                        parent: RecyclerView,
                        state: RecyclerView.State,
                        column: Int,
                        columnCount: Int,
                        row: Int,
                        rowCount: Int,
                        direction: Direction
                    ) = when {
                        direction == Direction.LEFT -> dp16
                        direction == Direction.RIGHT -> dp16
                        direction == Direction.TOP && row == 0 -> dp10
                        direction == Direction.BOTTOM && row == rowCount - 1 -> dp10
                        else -> dp5
                    }
                })
                mediaAdapter = MediaAdapter()
                adapter = mediaAdapter
            }
        }
    }

    override fun initListener() {
        super.initListener()
        dataBinding?.run {
            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (userInDragging) {
                        playFirst()
                    }
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    when (newState) {
                        RecyclerView.SCROLL_STATE_IDLE -> {
                            userInDragging = false
                            playFirst()
                        }

                        RecyclerView.SCROLL_STATE_DRAGGING -> {
                            userInDragging = true
                        }

                        RecyclerView.SCROLL_STATE_SETTLING -> {
                            userInDragging = false
                        }
                    }
                }
            })
        }
        localViewModel.run {
            localMediaItems.observe(viewLifecycleOwner) {
                dataBinding?.smartRefreshLayout?.run {
                    if (state == RefreshState.Refreshing) {
                        finishRefresh()
                    }
                }
                if (it != null) {
                    mediaAdapter?.setList(it)
                    PlayerManager.SINGLE_PLAYER.playList?.setList(it)
                }
            }
        }

    }

    private fun playFirst() {
        mediaLayoutManager?.run {
            val firstIndex = findFirstCompletelyVisibleItemPosition()
            if (firstIndex >= 0) {
                findViewByPosition(firstIndex)?.run {
                    findViewById<VideoView>(R.id.videoView).run {
                        if (VideoFloatWindow.instance.isShowing()) {
                            VideoFloatWindow.instance.startPlay(mediaInfo)
                        } else {
                            play()
                        }
                    }
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        if (localViewModel.localMediaItems.value.isNullOrEmpty()) {
            dataBinding?.smartRefreshLayout?.autoRefresh()
        }
    }

    override fun onResume() {
        super.onResume()
        PlayerManager.SINGLE_PLAYER.playList?.currMedia?.observe(
            viewLifecycleOwner,
            playingMediaListener
        )
    }

    override fun onPause() {
        PlayerManager.SINGLE_PLAYER.playList?.currMedia?.removeObserver(playingMediaListener)
        super.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mediaLayoutManager = null
        mediaAdapter = null
    }

    private inner class MediaAdapter :
        BaseQuickAdapter<MediaInfo, BaseViewHolder>(R.layout.item_local_list) {

        init {
            setOnItemClickListener { _, view, _ ->
                view.findViewById<VideoView>(R.id.videoView).run {
                    play()
                }
            }
        }

        override fun convert(holder: BaseViewHolder, item: MediaInfo) {
            holder.getView<VideoView>(R.id.videoView).run {
                mediaInfo = item

            }
        }

    }

}